package ua.kharkov.knure.dereza.summarytask4.command;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.dereza.summarytask4.core.Constants;
import ua.kharkov.knure.dereza.summarytask4.db.dao.*;
import ua.kharkov.knure.dereza.summarytask4.db.dao.mysql.MysqlDAOFactory;
import ua.kharkov.knure.dereza.summarytask4.db.dto.*;
import ua.kharkov.knure.dereza.summarytask4.db.bean.*;

/**
 * Client's list of cards command
 * 
 * @author dereza
 * 
 */
public class ClientListCardsCommand extends Command {

	private static final long serialVersionUID = 83026760400036760L;

	private static final Logger log = Logger
			.getLogger(ClientListCardsCommand.class);

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse res) {
		log.debug("Command started");

		// gets client's session
		HttpSession session = req.getSession(false);

		// gets ClientBean from session
		ClientBean clientBean = (ClientBean) session.getAttribute("clientbean");
		log.trace("Got clientbean  from session --> " + clientBean);

		// if clientBean == null forward to login page
		if (clientBean == null) {
			String forward = Constants.COMMAND_LOGOUT;
			return forward;
		}
		int clientId = clientBean.getId();

		// creates the required DAO generator
		MysqlDAOFactory mysqlFactory = (MysqlDAOFactory) DAOFactory
				.getDAOFactory(DAOFactory.MYSQL);

		// gets cardDAO
		CardDAO cardDAO = mysqlFactory.getCardDAO();

		// gets list of client's cards by given client id
		List<CardDTO> cardDTOList = cardDAO.findClientCardsByClientId(clientId);
		log.trace("Found in DB: listCards --> " + cardDTOList);

		// sort cards by currency
		Collections.sort(cardDTOList, new Comparator<CardDTO>() {
			public int compare(CardDTO o1, CardDTO o2) {
				int result = o1.getCurrency_id() - o2.getCurrency_id();
				return result == 0 ? 0 : result / (Math.abs(result));
			}
		});
		List<CardBean> cardBeanList = exchangeCardDtoTOBean(cardDTOList);
		log.trace("Replaced cardBean list --> " + cardBeanList);

		// puts cards list to the request
		req.setAttribute("cardbeanlist", cardBeanList);

		log.debug("Command finished");
		String forward = Constants.PAGE_CLIENT_LIST_CARDS;
		return forward;
	}

	/**
	 * Replaces currency_id and status_id to their name and puts it to CardBean
	 * 
	 * @param cardDTOList
	 * @return
	 */
	public static List<CardBean> exchangeCardDtoTOBean(List<CardDTO> cardDTOList) {
		log.trace("Began exchanging cardDTO to cardBean");

		// Container that will contain list of beans
		List<CardBean> cardBeanList = new LinkedList<CardBean>();
		CardBean cardBean = null;

		// creates the required DAO generator
		MysqlDAOFactory mysqlFactory = (MysqlDAOFactory) DAOFactory
				.getDAOFactory(DAOFactory.MYSQL);

		// gets currency and status dao
		CurrencyDAO currencyDAO = mysqlFactory.getCurrencyDAO();
		StatusDAO statusDAO = mysqlFactory.getStatusDAO();
		for (CardDTO cardDTO : cardDTOList) {
			cardBean = new CardBean();
			cardBean.setId(cardDTO.getId());
			cardBean.setCode(cardDTO.getCode());
			cardBean.setName(cardDTO.getName());
			cardBean.setBalance(cardDTO.getBalance());

			// gets currency and status dto, does necessary query
			CurrencyDTO currencyDTO = currencyDAO.findCurrencyById(cardDTO
					.getCurrency_id());
			cardBean.setCurrency(currencyDTO.getAbbreviation());
			StatusDTO statusDTO = statusDAO.findStatusById(cardDTO
					.getStatus_id());
			cardBean.setStatus(statusDTO.getName());

			// adds cardBean to list
			cardBeanList.add(cardBean);
			log.trace("added to cardBeanList --> " + cardBean);
		}
		return cardBeanList;
	}

	@Override
	public String toString() {
		return "ClientListCardsCommand";
	}
}
